import config from '@/config'
// import user from './store/modules/user.js'
import store from '../store/index.js'
import user from '../store/modules/user.js'
class HttpRequest {
	constructor() {}
	request (options = {}) {
		const url = config.baseUrl + options.url
		options.header = Object.assign({ 'content-type': "application/json", userId: 0}, options.header)
		
		let hideLoading = options.hideLoading || false;
		// console.log(JSON.stringify(options.header))
		/* if(!options.header.token){
			console.log("false----------------------in")
			options.header.token=store.state.user.token;
			if(null == options.header.token){
				uni.showToast({
					title:"请先登录",
					icon: 'none'
				})
				return uni.navigateTo({
					url:"/pages/login/index"
				})
			}
		} */
		if (options.method) {
			if (options.method === "POST" || options.method === 'post') {
				options.header = Object.assign({ 'content-type': "application/x-www-form-urlencoded" }, options.header)
			} else {
				Object.assign({ 'content-type': "application/json" }, options.header)
			}
		}
		if (!hideLoading) {
			uni.showLoading({
				title: '加载中...'
			});
		}
		return new Promise((resolve, reject) => {
			uni.request({
				...options,
				url: url,
				success: (res) => {
					if (res.statusCode && res.statusCode !== 200) {
						uni.showToast({
							title: "api错误" + res.errMsg,
							icon: 'none'
						});
						return;
					}
					if (res.data.code) {
						if (res.data.code != 200 && res.data.code !== '201') {
							uni.showToast({
								title: "" + res.data.msg,
								icon: 'none'
							});
							return;
						}
					}
					// 将结果抛出
					resolve(res)
				},
				// 请求失败
				fail: (e) => {
					uni.showToast({
						title: "" + e.data.msg,
						icon: 'none'
					});
					resolve(e.data);
				},
				//请求完成
				complete() {
					//隐藏加载
					if (!hideLoading) {
						uni.hideLoading();
					}
					resolve();
					return;
				}
			})
		})
	}
}
export default HttpRequest